package com.zhitong.money.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhitong.money.entity.Dept;
import com.zhitong.money.entity.Position;
import com.zhitong.money.exception.AddException;
import com.zhitong.money.exception.DeleteException;
import com.zhitong.money.exception.RepeatException;
import com.zhitong.money.exception.UpdateException;
import com.zhitong.money.mapper.DeptMapper;
import com.zhitong.money.mapper.PositionMapper;
import com.zhitong.money.services.api.IDeptService;
import com.zhitong.money.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DeptService implements IDeptService {
     Logger logger=LoggerFactory.getLogger(DeptService.class);

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private PositionMapper positionMapper;

    /**
     * 查询所有的部门
     * @return
     * @throws Exception
     */
    @Override
    public List<Dept> findAllDept() throws Exception {
        List<Dept> allDept = deptMapper.findAllDept();
        return allDept;
    }

    /**
     * 分页查询部门
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo findDeptByPage(Map<String,Object> map) throws Exception {
        int pageNum=map.containsKey("pageNum")?(int)map.get("pageNum"):1;
        int pageSize=map.containsKey("pageSize")?(int)map.get("pageSize"):5;
        PageHelper.startPage(pageNum,pageSize);
        List<Dept> allDept = deptMapper.findDeptByMap(map);
        PageInfo pageInfo=new PageInfo(allDept);
        return pageInfo;
    }

    @Override
    public List<Dept> findDeptByMap(Map<String, Object> map) throws Exception {
        List<Dept> deptByMap = deptMapper.findDeptByMap(map);
        return deptByMap;
    }

    @Override
    public Dept findDeptByTid(String tid) throws Exception {
        Dept deptByTid = deptMapper.findDeptByTid(tid);
        if (deptByTid==null){
            throw new NullPointerException("findDeptByTid:查询为空");
        }
        return deptByTid;
    }

    /**
     * 根据名称查找部门
     * @param name
     * @return
     * @throws Exception
     */
    @Override
    public Dept findDeptByName(String name) throws Exception {

        return null;
    }

    /**
     * 根据id查询部门
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Dept findDeptById(String id) throws Exception {
        Dept dept = deptMapper.findDeptById(id);
        if(dept==null){
            throw new NullPointerException("没有改部门");
        }
        return dept;
    }

    /**
     * 修改部门数据
     * @param
     * @throws Exception
     */
    @Transactional
    @Override
    public void updateDept(Map<String,Object> map) throws Exception {

        try {
            String id=(String) map.get("id");
            map.put("id",id);
            map.put("startTime",DateUtil.StrToDate1((String) map.get("startTime")));
            map.put("endTime",DateUtil.StrToDate1((String) map.get("endTime")));
            deptMapper.updateDept(map);


            //先把该部门下的所有职位设置成0(无部门)
            Map<String, Object> map1 = new HashMap<>();
            List<String> ids = positionMapper.findIdsByDid(id);
            if (ids!=null && !ids.isEmpty()) {
                map1.put("ids", ids);
                map1.put("did", "00");
                positionMapper.updatePositionByIds(map1);
            }
            //把更新后的职位加入该部门下
            List<String> a=(List<String>) map.get("position");
            if (a!=null && !a.isEmpty()) {
                map1.put("ids",a);
                map1.put("did",map.get("id"));
                positionMapper.updatePositionByIds(map1);
            }

        } catch (Exception e) {
            logger.error("update dept error:"+e.getMessage());
                if (e instanceof RepeatException){
                    throw e;
                }else{
                    throw new UpdateException();
                }
        }
    }

    /**
     * 删除部门数据
     * @param id
     * @throws Exception
     */
    @Transactional
    @Override
    public int delDeptById(String id) throws Exception {
        try {
            Map<String,Object> map=new HashMap<>();
            List<String> ids = positionMapper.findIdsByDid(id);
            //依赖不为0是,拒绝删除
            if(ids!=null && !ids.isEmpty()){
              return -1;
            }
            return deptMapper.delDeptById(id);
        } catch (Exception e) {
            logger.error("delete Dept error:"+e.getMessage());
           throw  new DeleteException();
        }
    }

    /**
     * 添加部门数据
     * @param
     * @throws Exception
     */
    @Transactional
    @Override
    public void addDept(Map<String,Object> map) throws Exception {
        String id=UUID.randomUUID().toString().replace("-","");
        String deptName=((String)map.get("name")).trim();
        Dept dept1 = deptMapper.findDeptByName(deptName);
        if (dept1!=null ){
            throw new RepeatException("部门重复");
        }
        try {
            map.put("id", id);
            deptMapper.addDept(map);
            List<String> position =(List<String>)map.get("position");
            if (position!=null && !position.isEmpty()){
                Map<String,Object> map1=new HashMap<>();
                map1.put("ids",position);
                map1.put("did",id);
                positionMapper.updatePositionByIds(map1);
            }
        } catch (Exception e) {
            logger.error("add Dept error:"+e.getMessage());
            if (e instanceof RepeatException){
                throw e;
            }else{
                throw new AddException();
            }
        }
    }

    @Override
    public int delDeptByIds(List<String> ids) throws Exception {
        try {
            Map<String,Object> map=new HashMap<>();
            List<String> pids =null;
            for (String id:ids) {
                List<String> ids1 = positionMapper.findIdsByDid(id);
                if (ids1==null||ids1.isEmpty()){
                    continue;
                }else{
                    pids.addAll(ids1);
                }
            }
            if (pids!=null && !pids.isEmpty()){
              return -1;
            }
            return deptMapper.delDeptByIds(ids);
        } catch (Exception e) {
            logger.error("del Depts error:"+e.getMessage());
            throw new DeleteException();
        }
    }
}
